#import "TopicManager.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJsonParser.h"
#import "TopicModel.h"
#import "DBManager.h"
#import "TopicReplyModel.h"
#import "RegexKitLite.h"
#import "CoreDataManager.h"
#import "UserManager.h"

@implementation TopicManager

@synthesize sortIndex, listShow, dbSort, gettingNext, gettingNew;
static int DEFAULTLIMIT = 10;

-(id)initWithSort:(int)pSortIndex :(NSString *)pDBsort :(NSString *)pHTTPsort :(id<TopicManagerDelegate>) pDelegate {
    self = [super init];
    if (self) {
        sortIndex = pSortIndex;
        dbSort = pDBsort;
        httpSort = pHTTPsort;
        
        //text%7Cimage
        urlPrx = TOPIC_INITWITHSORT_URL(httpSort);
        //urlPrx = [[NSString stringWithFormat:@"http://lengxiaohua.com/lengxiaohuaapi/gather?action=getGathers&type=%@",httpSort]retain];
        
        delegate = pDelegate;
        backIndex = 0;
        listLocal = [[NSMutableArray alloc] init];
        listShow = [[NSMutableArray alloc] init];
        setShow = [[NSMutableSet alloc] init];
        listNext = [[NSMutableArray alloc] init];
        dicLocal = [[NSMutableDictionary alloc] init];
        gettingNew = NO;
        gettingNext = NO;
        started = NO;
        [[DBManager sharedInstance] createTopicTable:dbSort];
        NSMutableArray *listAll = [[[DBManager sharedInstance] getAllTopicSummary:dbSort] retain];
        NSMutableArray *ids2Del = [[NSMutableArray alloc] init];
        int index = listAll.count - 1;
        int count = 0;
        for( ; index>=0; --index ){
            TopicModel *one = [listAll objectAtIndex:index];
            if( ++count <= 100 ){
                [listLocal addObject:one];
                [listShow addObject:one];
                [setShow addObject:one.topicId];
                [dicLocal setObject:one forKey:one.topicId];
            } else {
                [ids2Del addObject:one.topicId];
            }
        }
        Log(@"local: all/del/left : %d/%d/%d",listAll.count,ids2Del.count,listLocal.count);
        [listAll removeAllObjects];
        [listAll release];
        if( ids2Del.count > 0 ){
            [[DBManager sharedInstance] deleteTopics:dbSort :ids2Del];
            [[CoreDataManager sharedInstance]deleteAllTopicDetailForCoredata:dbSort :ids2Del];
        }
        [ids2Del release];
    }
    return self;
}

- (void) dealloc
{
    PP_RELEASE(urlPrx);
    PP_RELEASE(httpSort);
    PP_RELEASE(listNext);
    PP_RELEASE(listLocal);
    PP_RELEASE(setShow);
    PP_RELEASE(dicLocal);
    PP_RELEASE(delegate);
    PP_RELEASE(dbSort);
    PP_RELEASE(listShow);
    [super dealloc];
}

-(void)startAsync {
    if(started) {
        return;
    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self httpNewSync:YES];
        [self httpNextSync];
    });
    started = YES;
}

#pragma -------------New---------------------

-(void)getNewAsync {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self httpNewSync :NO];
    });
}

-(void)httpNewSync:(BOOL)initing {
    @synchronized(self){
        if(self.gettingNew){
            [delegate TMloadNew:self :0 :initing];
            return;
        }
        self.gettingNew = YES;
    }
    int tIndex = listShow.count;
    if(tIndex == 0){
        tIndex = DEFAULTLIMIT;
    }
    
//    NSString *url = [NSString stringWithFormat:@"%@&start=%d&limit=%d",urlPrx,0,tIndex];
    NSString *url = TOPIC_WITHSORT_URL(httpSort, 0, tIndex);
    
//    Log(@"getting: %@",url);
//    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
//    request.userAgentString = @"lxh_app2_100";
//    [request setRequestMethod:@"GET"];
//    [request setAllowCompressedResponse:YES];
//    [request setDelegate:self];
////    [request setDidFinishSelector:@selector(requestNewDone:)];
////    [request setDidFailSelector:@selector(requestNewFaild:)];
//    [request startSynchronous];
    ASIHttpRequset_GET(url, NO);
    NSError *err = [request error];
    if(!err){
        [self requestNewDone:request :initing];
    }else{
        [self requestNewFailed:request];
    }
    [delegate TMloadNew:self :0 :initing];
    @synchronized(self){
        self.gettingNew = NO;
    }
}

- (void)requestNewDone:(ASIHTTPRequest *)request :(BOOL)initing {
    NSMutableArray *tHttpTopics = [[NSMutableArray alloc] init];
    NSString *tResponseStr = [request responseString];
    //    Log(@"res: %@",tResponseStr);
    SBJsonParser *tJsonParser = [[SBJsonParser alloc] init];
    id tJsonObjects = [tJsonParser objectWithString:tResponseStr];
    [tJsonParser release], tJsonParser = nil;
    if ([tJsonObjects isKindOfClass:[NSDictionary class]]){
        NSMutableArray *tTopicsStr = [(NSDictionary *)tJsonObjects mutableArrayValueForKey:@"gathers"];
        for (NSDictionary *tTopicStr in tTopicsStr)
        {
            if(initing){
                backIndex++;
            }
            TopicModel *tTopic = [[TopicModel alloc] init];
            [tTopic setTopicId:[[tTopicStr objectForKey:@"Gatherid"] stringValue]];
            [tTopic setTopicTime:[tTopicStr objectForKey:@"created_cn"]];
            [tTopic setTopicTitle:[tTopicStr objectForKey:@"title"]];
            [tTopic setTopicText:[tTopicStr objectForKey:@"summary"]];
            NSString *topicImgUrl = [tTopicStr objectForKey:@"uri_100x100"];
            if(topicImgUrl.length==0){
                [tTopic setTopicImgUrl:topicImgUrl];
            }else{
                if([topicImgUrl hasPrefix:@"http"]){
                    [tTopic setTopicImgUrl:topicImgUrl];
                }else{
                    [tTopic setTopicImgUrl:COMPLEMENTED_URL(topicImgUrl)];
                }
            }
            [tHttpTopics addObject:tTopic];
            [tTopic release];
        }
    }else{
        Log(@"get 0");
    }
    
    NSMutableArray *listToDown = [[NSMutableArray alloc] init];
    NSMutableArray *listNew = [[NSMutableArray alloc] init];
    for (TopicModel *one in tHttpTopics)
    {
        TopicModel *hit = [dicLocal objectForKey:one.topicId];
        if( hit != nil ) { //本地已经存在
            //            Log(@"refresh : %@",hit.topicId);
            if( ![setShow containsObject:one.topicId]){ //显示列表中不含
                [listNew addObject:one];
            }
        }else{ // 本地不含
            [listToDown addObject:one];
            [listNew addObject:one];
        }
    }
    [tHttpTopics removeAllObjects];
    [tHttpTopics release];
    
    NSMutableArray *listNotify = [[NSMutableArray alloc] init];
    int indexN = listNew.count - 1;
    int indexD = listToDown.count - 1;
    while( indexN >=0 ) {
        TopicModel * oneNew  = [listNew objectAtIndex:indexN];
        TopicModel * oneDown =  indexD>=0?[listToDown objectAtIndex:indexD]:nil;
        if( oneNew == oneDown ){
            Log(@"loading : %@",oneNew.topicId);
            TopicModel *tTopic = [oneNew copy];
            
//            if(tTopic.topicImgUrl.length!=0){
//                tTopic.topicImg = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:tTopic.topicImgUrl]]];
//            }
            
            [[DBManager sharedInstance] saveTopic:dbSort :tTopic];
            [tTopic release];
            [listLocal addObject:oneDown];
            [dicLocal setObject:oneDown forKey:oneDown.topicId];
            indexN --;
            indexD --;
        }else{
            indexN --;
        }
        if( initing && listShow.count>=8 ){
            [listNotify addObject:oneNew];
        }else{
            TopicModel *one = [dicLocal objectForKey:oneNew.topicId];
            [listShow insertObject:one atIndex:0];
            [setShow addObject:one.topicId];
            [delegate TMloadNew:self :1 :initing];
        }
    }
    if( listNotify.count > 0 ){
        for( TopicModel *oneNotify in listNotify ){
            TopicModel *one = [dicLocal objectForKey:oneNotify.topicId];
            [listShow insertObject:one atIndex:0];
            [setShow addObject:one.topicId];
        }
        [delegate TMloadNew:self :listNotify.count :initing];
    }
    
    [listNotify removeAllObjects];
    [listNew removeAllObjects];
    [listToDown removeAllObjects];
    [listNotify release];
    [listNew release];
    [listToDown release];
}

- (void)requestNewFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    Log(@"res : %@",[error description]);
}

-(void)getNextAsync {
    Log(@"show next : %d",listNext.count);
    if(listNext.count != 0){
        int nextCount = 0;
        for( TopicModel *one in listNext ){
            if( [setShow containsObject:one.topicId] ){
                continue;
            }
            ++nextCount;
            [listShow addObject:one];
            [setShow addObject:one.topicId];
        }
        [delegate TMloadNext:self :nextCount];
    }
    [delegate TMloadNext:self :0];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self httpNextSync];
    });
}

-(void)httpNextSync
{
    @synchronized(self){
        if(self.gettingNext){
            return;
        }
        self.gettingNext = YES;
        [listNext removeAllObjects];
    }
    
//    NSString *url = [NSString stringWithFormat:@"%@&start=%d&limit=%d",urlPrx,backIndex,DEFAULTLIMIT];
    NSString *url = TOPIC_WITHSORT_URL(httpSort, backIndex, DEFAULTLIMIT);

    //    Log(@"getting: %@",url);
//    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
//    request.userAgentString = @"lxh_app2_100";
//    [request setRequestMethod:@"GET"];
//    [request setAllowCompressedResponse:YES];
//    [request setDelegate:self];
//    [request startSynchronous];
    ASIHttpRequset_GET(url, NO);
    NSError *err = [request error];
    if(!err){
        [self requestNextDone:request];
    }else{
        [self requestNextFailed:request];
    }
    @synchronized(self){
        self.gettingNext = NO;
    }
}

- (void)requestNextDone:(ASIHTTPRequest *)request
{
    NSMutableArray *tHttpTopics = [[NSMutableArray alloc] init];
    NSString *tResponseStr = [request responseString];
    //    Log(@"tResponseStr :%@",tResponseStr);
    SBJsonParser *tJsonParser = [[SBJsonParser alloc] init];
    id tJsonObjects = [tJsonParser objectWithString:tResponseStr];
    [tJsonParser release], tJsonParser = nil;
    if ([tJsonObjects isKindOfClass:[NSDictionary class]]){
        NSMutableArray *tTopicsStr = [(NSDictionary *)tJsonObjects mutableArrayValueForKey:@"gathers"];
        Log(@"get next : %d",tTopicsStr.count);
        for (NSDictionary *tTopicStr in tTopicsStr)
        {
            ++backIndex;
            TopicModel *tTopic = [[[TopicModel alloc] init] autorelease];
            [tTopic setTopicId:[[tTopicStr objectForKey:@"Gatherid"] stringValue]];
            [tTopic setTopicTime:[tTopicStr objectForKey:@"created_cn"]];
            [tTopic setTopicTitle:[tTopicStr objectForKey:@"title"]];
            [tTopic setTopicText:[tTopicStr objectForKey:@"summary"]];
            NSString *topicImgUrl = [tTopicStr objectForKey:@"uri_100x100"];
            if(topicImgUrl.length==0){
                [tTopic setTopicImgUrl:topicImgUrl];
            }else{
                if([topicImgUrl hasPrefix:@"http"]){
                    [tTopic setTopicImgUrl:topicImgUrl];
                }else{
                    [tTopic setTopicImgUrl:COMPLEMENTED_URL(topicImgUrl)];
                }
            }
            [tHttpTopics addObject:tTopic];
        }
    }else{
        Log(@"get next : 0");
    }
    
    NSMutableArray *listToDown = [[NSMutableArray alloc] init];
    NSMutableArray *tListNext = [[NSMutableArray alloc] init];
    for (TopicModel *one in tHttpTopics)
    {
        TopicModel *hit = [dicLocal objectForKey:one.topicId];
        if( hit != nil ) { //本地已经存在
            //            Log(@"refresh : %@",hit.topicId);
            if( ![setShow containsObject:one.topicId] ){ //显示列表中不含
                [tListNext addObject:one];
            }
        }else{ // 本地不含
            [listToDown addObject:one];
            [tListNext addObject:one];
        }
    }
    //    Log(@" test %d %d %d",tListNext.count, listToDown.count, tHttpTopics.count);
    [tHttpTopics removeAllObjects];
    [tHttpTopics release];
    
    for (TopicModel *oneDown in listToDown)
    {
        Log(@"loading : %@",oneDown.topicId);
        TopicModel *tTopic = [oneDown copy];
        
//        if(tTopic.topicImgUrl.length!=0){
//            tTopic.topicImg = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:tTopic.topicImgUrl]]];
//        }
        
        [[DBManager sharedInstance] saveTopic:dbSort :tTopic];
        [tTopic release];
        [listLocal addObject:oneDown];
        [dicLocal setObject:oneDown forKey:oneDown.topicId];
    }
    
    for( TopicModel *one in tListNext ){
        [listNext addObject:[dicLocal objectForKey:one.topicId]];
    }
    //    Log(@" test %d %d %d",tListNext.count, listToDown.count, listNext.count);
    
    [tListNext removeAllObjects];
    [listToDown removeAllObjects];
    [tListNext release];
    [listToDown release];
}

- (void)requestNextFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    Log(@"res : %@",[error description]);
}

#pragma -----------获得单个编辑推荐---------

-(TopicModel *)httpTopicDetail:(NSString *)topicId {
    NSString *url = TOPIC_DETAILSINGEL_URL(topicId);
    //   NSString *url = [NSString stringWithFormat:@"http://lengxiaohua.com/lengxiaohuaapi/gather?action=getOneGather&Gatherid=%@",topicId];
    
    //    Log(@"getting: %@",url);
//    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
//    request.userAgentString = @"lxh_app2_100";
//    [request setRequestMethod:@"GET"];
//    [request setAllowCompressedResponse:YES];
//    [request setDelegate:self];
//    [request startSynchronous];
    ASIHttpRequset_GET(url, NO);
    NSError *err = [request error];
    if(!err){
        return [self requestTopicDetailDone:request];
    }else{
        [self requestTopicDetailFailed:request];
    }
    return nil;
}

#pragma -------------detail--------------------
- (TopicModel *)requestTopicDetailDone:(ASIHTTPRequest *)request
{
    NSString *tResponseStr = [request responseString];
    
    //    Log(@"res-------------------: %@",tResponseStr);
    TopicModel *tTopicModel = [[[TopicModel alloc] init] autorelease];
    SBJsonParser *tJsonParser = [[SBJsonParser alloc] init];
    id tTopicStr = [tJsonParser objectWithString:tResponseStr];
    [tJsonParser release], tJsonParser = nil;
    NSString *tContent = @"服务器错误，请稍后再试";
    if ([tTopicStr isKindOfClass:[NSDictionary class]]){
        tTopicModel.topicId = [[tTopicStr objectForKey:@"Gatherid"] stringValue];
        tTopicModel.topicTitle = [tTopicStr objectForKey:@"title"];
        tTopicModel.topicTime = [tTopicStr objectForKey:@"created_cn"];
        tContent = [tTopicStr objectForKey:@"content"];
        NSString *topicImgUrl = [tTopicStr objectForKey:@"uri"];
        if(topicImgUrl.length==0){
            [tTopicModel setTopicImgUrl:topicImgUrl];
        }else{
            if([topicImgUrl hasPrefix:@"http"]){
                [tTopicModel setTopicImgUrl:topicImgUrl];
            }else{
                [tTopicModel setTopicImgUrl:COMPLEMENTED_URL(topicImgUrl)];
            }
        }
        
        NSMutableArray * imgs = [tTopicStr objectForKey:@"images"];
        
        NSMutableDictionary * imgsDic = [[[NSMutableDictionary alloc] init] autorelease];
        
        for( NSDictionary* one in imgs ){
            NSString *key = [[one objectForKey:@"UserImageid"] stringValue];
            NSString *value = [one objectForKey:@"uri"];
            //            Log(@"set %@ for %@",value,key);
            [imgsDic setObject:value forKey:key];
        }
        
        NSString *regexString  = @"\(\\[image.*\?)\\s*\\]";
        NSArray  *splitArray   = NULL;
        splitArray = [tContent componentsSeparatedByRegex:regexString];
        Log(@"splitArray :%@",splitArray);
        for( NSString* one in splitArray ){
            NSString *tRes    = one;
            if([one hasPrefix:@"[image"]){
                if([one hasPrefix:@"[image_"]){
                    tRes = [tRes stringByReplacingOccurrencesOfRegex:@"\\[image_\(.*\?)" withString:@"$1"];
                    tRes = [imgsDic objectForKey:tRes];
                    if (tRes == NULL) {
                        return nil;
                        break;
                    }
                    
                }else{
                    tRes = [tRes stringByReplacingOccurrencesOfRegex:@"\\[image\\s+\(.*\?)" withString:@"$1"];
                    if (tRes == NULL) {
                        return nil;
                        break;
                    }
                }
                if(![tRes hasPrefix:@"http"]){
                    if (tRes == NULL) {
                        return nil;
                        break;
                    }
                    tRes = COMPLEMENTED_URL(tRes);
                }
            }
            [tTopicModel.topicContent addObject:tRes];
        }
        
        //        Log(@"splitArray is :%@",splitArray);
    }else{
        Log(@"get 0");
    }
    return  tTopicModel;
}

- (void)requestTopicDetailFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    Log(@"%@",[error description]);
}

-(NSMutableArray *)httpGetReplySync:(NSString *)topicId
{
    NSString *url = TOPIC_DETAIL_REPLY_URL(topicId);
    //    Log(@"getting: %@",url);
//    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
//    request.userAgentString = @"lxh_app2_100";
//    [request setRequestMethod:@"GET"];
//    [request setAllowCompressedResponse:YES];
//    [request setDelegate:self];
//    [request startSynchronous];
    ASIHttpRequset_GET(url, NO);
    NSError *err = [request error];
    if(!err){
        return [self requestReplyFinished:request];
    }else{
        [self requestReplyFailed:request];
        return nil;
    }
}

- (NSMutableArray *)requestReplyFinished:(ASIHTTPRequest *)request
{
    NSString *tResponseStr = [request responseString];
    //    Log(@"res : %@",tResponseStr);
    SBJsonParser *tJsonParser = [[SBJsonParser alloc] init];
    id tJsonObjects = [tJsonParser objectWithString:tResponseStr];
    [tJsonParser release], tJsonParser = nil;
    if ([tJsonObjects isKindOfClass:[NSDictionary class]]){
        NSMutableArray *tReplies = [(NSDictionary *)tJsonObjects mutableArrayValueForKey:@"comments"];
        Log(@"get next : %d",tReplies.count);
        NSMutableArray *resReplies = [[NSMutableArray alloc] init];
        for (NSDictionary *tTopic in tReplies)
        {
            NSDictionary *tAuthor = [tTopic objectForKey:@"author"];
            TopicReplyModel *tReply = [[[TopicReplyModel alloc] init] autorelease];
            [tReply setReplyName:[tAuthor objectForKey:@"username"]];
            [tReply setReplyText:[tTopic objectForKey:@"content"]];
            [resReplies addObject:tReply];
        }
        return [[resReplies retain] autorelease];
    }
    return nil;
}

- (void)requestReplyFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    Log(@"err : %@",[error description]);
}

-(void)clearTopicData{
    NSMutableArray *idsArr = [[[NSMutableArray alloc]init]autorelease];
    for (NSObject *object in dicLocal) {
        [idsArr addObject:object];
    }
    [[CoreDataManager sharedInstance]deleteAllTopicDetailForCoredata:dbSort :idsArr];
    
    [listNext removeAllObjects];
    [listLocal removeAllObjects];
    [setShow removeAllObjects];
    [dicLocal removeAllObjects];
    [listShow removeAllObjects];
    PP_RELEASE(listNext);
    PP_RELEASE(listLocal);
    PP_RELEASE(setShow);
    PP_RELEASE(dicLocal);
    PP_RELEASE(listShow);
}

@end
